package com.jrx.anytxn.transaction.service.impl;

import com.jrx.anytxn.common.data.TxnRespCode;
import com.jrx.anytxn.common.exception.TxnBizException;
import com.jrx.anytxn.common.uitl.StringUtils;
import com.jrx.anytxn.number.exception.SegmentException;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.entity.PrGuaranteeTable;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.entity.PrProductTable;
import com.jrx.anytxn.param.mapper.ext.ExtPrGuaranteeTableMapper;
import com.jrx.anytxn.param.mapper.ext.ExtPrProductTableMapper;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.entity.AmLoanAccountInfo;
import com.jrx.anytxn.transaction.entity.AmRepaymentPlanInfo;
import com.jrx.anytxn.transaction.entity.BtGuaranteeList;
import com.jrx.anytxn.transaction.mapper.ext.ExtAmRepaymentPlanInfoMapper;
import com.jrx.anytxn.transaction.service.ICmpsCrtService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CmpsCrtServiceImpl implements ICmpsCrtService {

    private static final Logger logger = LoggerFactory.getLogger(ChargeoffServiceImpl.class);

    @Resource
    private ExtPrProductTableMapper extPrProductTableMapper;
    @Resource
    private ExtPrGuaranteeTableMapper extPrGuaranteeTableMapper;
    @Resource
    private ExtAmRepaymentPlanInfoMapper extAmRepaymentPlanInfoMapper;
    @Autowired
    private ISegmentService segmentService;
    @Autowired
    private IOrganizationTableService organizationTableService;

    @Override
    public BtGuaranteeList createGuarantee(AmLoanAccountInfo accountInfo) throws Exception {
        logger.info("代偿回购判断处理，订单编号：{}",accountInfo.getLoanId());
        //1 产品编号查询产品信息
        PrProductTable prProductTable = extPrProductTableMapper.selectByProductIdAndStatus(
                accountInfo.getProductId(), TransBizConstant.STATUS_1,accountInfo.getTenantId());
        if(StringUtils.isBlank(prProductTable.getGuaranteeId())){
            logger.error("产品未设置代偿回购参数编号，产品编号:{}",prProductTable.getProductId());
            return null;
        }
        //2 根据产品编号查询 代偿回购 参数
        PrGuaranteeTable prGuaranteeTable = extPrGuaranteeTableMapper.selectByGuaranteeId(prProductTable.getGuaranteeId());
        if(prGuaranteeTable == null){
            logger.error("未获取到对应的代偿回购参数，参数编号：{}",prProductTable.getGuaranteeId());
            return null;
        }
        Boolean isCrt = false;//是否满足回购条件
        //3 判断是否满足回购条件
        if(prGuaranteeTable.getBalTransFlag().equals(TransBizConstant.YES_FLAG)){
            switch (prGuaranteeTable.getBalTransMethod()){
                case TransBizConstant.BAL_TRANS_MOTHOD_CONTINUE://连续逾期期数判断
                    if(prGuaranteeTable.getContinueDelqTenor() != null) {
                        if(accountInfo.getContinueOverDueTenor().compareTo(prGuaranteeTable.getContinueDelqTenor()) >= 0){
                            isCrt = true;
                        }
                    }
                    break;
                case TransBizConstant.BAL_TRANS_MOTHOD_CMPS://连续代偿次数
                    if(prGuaranteeTable.getContinueCompensatoryTenor() != null){
                        //连续代偿次数计算
                        int couNumber = countContinueCmps(accountInfo);
                        if(couNumber >= prGuaranteeTable.getContinueCompensatoryTenor()){
                            isCrt = true;
                        }
                    }
                    break;
                case TransBizConstant.BAL_TRANS_MOTHOD_TOTAL_CONTINUE://总逾期期数
                    if(prGuaranteeTable.getTotalDelqTenor() != null){
                        if(accountInfo.getTotalOverDueTenor().compareTo(prGuaranteeTable.getTotalDelqTenor()) >= 0){
                            isCrt = true;
                        }
                    }
                    break;
                case TransBizConstant.BAL_TRANS_MOTHOD_TOTAL_CMPS://总代偿次数
                    if(prGuaranteeTable.getTotalCompensatoryTenor() != null){
                        int totalCmps = extAmRepaymentPlanInfoMapper.selectCountByCmps(accountInfo.getLoanId(),
                                accountInfo.getCustomerId(),accountInfo.getTenantId());
                        if(totalCmps >= prGuaranteeTable.getTotalCompensatoryTenor()){
                            isCrt = true;
                        }
                    }
                    break;
                case TransBizConstant.BAL_TRANS_MOTHOD_TOTAL_CON://连续逾期或累计逾期期数
                    if(prGuaranteeTable.getContinueDelqTenor() != null) {
                        if(accountInfo.getContinueOverDueTenor().compareTo(prGuaranteeTable.getContinueDelqTenor()) >= 0||
                                accountInfo.getTotalOverDueTenor().compareTo(prGuaranteeTable.getContinueDelqTenor()) >= 0){
                            isCrt = true;
                        }
                    }
                    break;
                case TransBizConstant.BAL_TRANS_MOTHOD_TOTAL_CON_CMPS://连续代偿或累计代偿期数
                    if(prGuaranteeTable.getTotalCompensatoryTenor() != null){
                        //连续代偿次数计算
                        int couNumber = countContinueCmps(accountInfo);
                        //总代偿次数
                        int totalNumber = extAmRepaymentPlanInfoMapper.selectCountByCmps(accountInfo.getLoanId(),
                                accountInfo.getCustomerId(),accountInfo.getTenantId());
                        if(couNumber >= prGuaranteeTable.getTotalCompensatoryTenor() ||
                                totalNumber >= prGuaranteeTable.getTotalCompensatoryTenor()){
                            isCrt = true;
                        }
                    }
                    break;
                case TransBizConstant.BAL_TRANS_MOTHOD_DAY://逾期天数
                    if(prGuaranteeTable.getBalTransDays() != null){
                        if(accountInfo.getDelqDays().compareTo(prGuaranteeTable.getBalTransDays()) >= 0 ){
                            isCrt = true;
                        }
                    }
                    break;
            }

        }
        if(isCrt){
            //满足回购条件
            return buildGuarantee(accountInfo,TransBizConstant.REPAYMENT_TYPE_CRT);
        }

        //4 不满足回购条件再判断是否满足代偿条件
        if(prGuaranteeTable.getCompensatoryFlag().equals(TransBizConstant.YES_FLAG)){
            if(prGuaranteeTable.getCompensatoryDays() != null){
                if(accountInfo.getDelqDays().compareTo(prGuaranteeTable.getCompensatoryDays()) >= 0){
                    //满足代偿条件
                    return buildGuarantee(accountInfo,TransBizConstant.REPAYMENT_TYPE_CMPS);
                }
            }
        }
        return null;
    }

    /**
     * 根据订单账户计算连续代偿次数
     * @param info
     * @return
     */
    private int countContinueCmps(AmLoanAccountInfo info){
        int conNumber = 0;//连续代偿次数
        //1 根据订单查询还款计划 升序
        List<AmRepaymentPlanInfo> planList = extAmRepaymentPlanInfoMapper.selectByLoanIdAsc(info.getLoanId(),
                info.getCustomerId(),info.getTenantId());
        for(int i = 0 ; i < planList.size() ; i++){
           if(planList.get(i).getCompensateFlag().equals(TransBizConstant.YES_FLAG)){
               if(planList.get(i).getBillingTenor() == 1){
                   conNumber ++;
               }else if(planList.get(i - 1).getCompensateFlag().equals(TransBizConstant.YES_FLAG)){
                   conNumber ++;
               }
           }
        }
        return conNumber;
    }

    /**
     * 根据订单生成数据准备记录
     * @param info
     * @return
     */
    private BtGuaranteeList buildGuarantee(AmLoanAccountInfo info,String paymentType) throws TxnBizException{
        BtGuaranteeList btGuaranteeList = new BtGuaranteeList();
        try {
            btGuaranteeList.setId(segmentService.getId(TransBizConstant.BT_GUARANTEE_LIST_ID));
        } catch (SegmentException e) {
            logger.error("主键生成错误", e);
            throw new TxnBizException(TxnRespCode.ERROR.getUserTips());
        }
        btGuaranteeList.setLoanId(info.getLoanId());
        btGuaranteeList.setOrganizationId(info.getOrganizationId());
        btGuaranteeList.setTenantId(info.getTenantId());
        btGuaranteeList.setChannel(info.getChannel());
        btGuaranteeList.setProductId(info.getProductId());
        btGuaranteeList.setCustomerId(info.getCustomerId());
        btGuaranteeList.setPaymentType(paymentType);
        btGuaranteeList.setUpdateBy(TransBizConstant.SYS_OPRATE);
        btGuaranteeList.setRecordVersionNumber(TransBizConstant.INIT_RECORD_VERSION_NUMBER);
        PrOrganizationTable organizationTable=organizationTableService.findByOrId(info.getOrganizationId(),info.getTenantId());
        btGuaranteeList.setBusinessDate(organizationTable.getNextProcessingDate());
        return btGuaranteeList;
    }
}
